package switchviz.graphic.signal;

import org.jdom.Element;

public class SimpleSignalPersistence extends BasicSignalPersistence
{
	private final static String SIGALIAS = "alias";
	private final static String OFFSET = "offset";
	private final static String COEFFICIENT = "coefficient";
	private final static String PORT = "port";
	private final static String PORTREQUIRED = "portrequred";
	private final static String DIFFERENCE = "difference";
	private final static String LOGARITHM = "logarithm";
	
	private SimpleSignalDataModel _datamodel = null;
	
	public SimpleSignalPersistence(Element root) 
	{
		super(root);
	}

	public SimpleSignalDataModel getDataModelFromElement()
	{
		super.getDataModelFromElementBasic();
		if(_root.getChild(SIGALIAS) != null)
			getDataModel().setAlias(_root.getChildText(SIGALIAS));
		if(_root.getChild(OFFSET) != null)
			getDataModel().setOffset(Float.parseFloat(_root.getChildText(OFFSET)));
		if(_root.getChild(COEFFICIENT) != null)
			getDataModel().setCoefficient(Float.parseFloat(_root.getChildText(COEFFICIENT)));
		if(_root.getChild(PORT) != null)
			getDataModel().setPort(Integer.parseInt(_root.getChildText(PORT)));
		if(_root.getChild(PORTREQUIRED) != null)
			getDataModel().setPortrequired(Integer.parseInt(_root.getChildText(PORTREQUIRED)));
		if(_root.getChild(DIFFERENCE) != null)
			getDataModel().setDifference(Boolean.parseBoolean(_root.getChildText(DIFFERENCE)));
		if(_root.getChild(LOGARITHM) != null)
			getDataModel().setLogarithm(Boolean.parseBoolean(_root.getChildText(LOGARITHM)));
			
		return getDataModel();
	}
	
	public Element setDataModel(SimpleSignalDataModel datamodel)
	{
		_datamodel = datamodel;
		
		return saveDataModel();
	}
	
	protected SimpleSignalDataModel getDataModel()
	{
		if (_datamodel == null) 
			_datamodel = new SimpleSignalDataModel();
		
		return _datamodel;
	}
	
	protected Element saveDataModel()
	{
		super.saveDataModel();
		addNode(SIGALIAS, getDataModel().getAlias());
		addNode(OFFSET, String.valueOf(getDataModel().getOffset()));
		addNode(COEFFICIENT, String.valueOf(getDataModel().getCoefficient()));
		addNode(PORT, String.valueOf(getDataModel().getPort()));
		addNode(PORTREQUIRED, String.valueOf(getDataModel().getPortrequired()));
		addNode(DIFFERENCE, String.valueOf(getDataModel().isDifference()));
		addNode(LOGARITHM, String.valueOf(getDataModel().isLogarithm()));
		return _root;
	}
	
	public Element getElement()
	{
		return _root;
	}
}
